import { request } from '@doctorwork/saga';

export default {
    namespace: 'cityList',
    state: {
        province: [],
        city: [],
        district: []
    },
    reducers: {
        save: (state, { payload }) => {
            return Object.assign({}, { ...state, ...payload });
        }
    },
    effects: {
        *getProvinceList({ payload }, { put, select }) {
            const province = yield put.resolve(
                request.get({
                    url: '/api/region/query/child?parentCode='
                })
            );

            yield put({
                type: 'save',
                payload: {
                    province
                }
            });

            const sel_ = payload.selected[0];
            if (province.length) {
                yield put({
                    type: 'getCityList',
                    payload: {
                        areaCode: sel_ ? sel_ : province[0].areaCode,
                        selected: payload.selected
                    }
                });
            } else {
                yield put({
                    type: '$error/other',
                    payload: { errmsg: '网络错误' }
                });
            }
        },
        *getCityList({ payload }, { put, select }) {
            const city = yield put.resolve(
                request.get({
                    url: `/api/region/query/child?parentCode=${
                        payload.areaCode
                    }`
                })
            );

            yield put({
                type: 'save',
                payload: {
                    city
                }
            });
            const sel_ = payload.selected[1];
            if (city.length) {
                yield put({
                    type: 'getDistrictList',
                    payload: {
                        areaCode: sel_ ? sel_ : city[0].areaCode
                    }
                });
            }
        },
        *getDistrictList({ payload }, { put, select }) {
            const district = yield put.resolve(
                request.get({
                    url: `/api/region/query/child?parentCode=${
                        payload.areaCode
                    }`
                })
            );

            yield put({
                type: 'save',
                payload: {
                    district
                }
            });
        }
    }
};
